import json

from flask import Blueprint, request
from pypinyin import lazy_pinyin
from sqlalchemy import and_, desc

from .models import HotelInfo, HotelRoomTypeInfo

hotel_bp = Blueprint('hotel', __name__, url_prefix='/hotels')

@hotel_bp.route('/')
def list_hotels():
    page_no = request.args.get('page_no', 1, type=int)  # 获取页码参数
    page_size = request.args.get('page_size', 20, type=int)  # 每页数量
    city_id = request.args.get('city_id', 0, type=int)  # 每页数量
    search_content = request.args.get('search_content', '')
    sort_by = request.args.get('sort_by', 'id')
    sort_order = request.args.get('sort_order', 'asc')

    # 验证字段合法性（防止 SQL 注入）
    valid_fields = {'id', 'last_update'}
    if sort_by not in valid_fields:
        sort_by = 'id'

    # 构建排序条件
    if sort_order.lower() == 'desc':
        order_expr = desc(getattr(HotelInfo, sort_by))
    else:
        order_expr = getattr(HotelInfo, sort_by)

    filters = []
    # 根据条件动态添加过滤
    if city_id > 0:
        filters.append(HotelInfo.city_id == city_id)
    if len(search_content) > 0:
        filters.append(HotelInfo.name.like('%' + search_content + '%'))

    # 执行分页查询
    pagination = (HotelInfo.query.filter(and_(*filters)).order_by(order_expr).paginate(
        page=page_no,
        per_page=page_size,
        error_out=False  # 当页码超出范围时返回空而不是404
    ))

    return {
        'data': [h.to_dict() for h in pagination.items],
        'total': pagination.total,
        'page_total': pagination.pages,
        'page_no': pagination.page,
        'page_size': pagination.per_page
    }


@hotel_bp.route('/<int:hotel_id>', methods=('GET',))
def get_hotel_detail(hotel_id):
    hotelDetail = HotelInfo.query.filter_by(id=hotel_id).first()

    return hotelDetail.to_dict()


@hotel_bp.route('/<int:hotel_id>/room_types', methods=('GET',))
def get_hotel_room_types(hotel_id):
    list = HotelRoomTypeInfo.query.filter_by(hotel_id=hotel_id).all()

    return {
        'data': [h.to_dict() for h in list]
    }